package org.springblade.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class UrlFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public void doFilter(final ServletRequest request, final ServletResponse res,
            final FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        String path = httpRequest.getRequestURI();

        // response.setHeader("Access-Control-Allow-Origin", "*");// * 表示该资源谁都可以用,从而实现跨域
        // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        // response.setHeader("Access-Control-Max-Age", "3600");
        // response.setHeader("Access-Control-Allow-Headers", "*");
        // HttpServletRequest request = (HttpServletRequest) req;

        logger.info(httpRequest.getMethod().toString()
                + " UrlFilter ---------------------------------------- " + path);

        // if (httpRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
        // logger.error("pass OPTIONS ---------------------------------------- " + path);
        // }

        if (!StringUtils.hasText(path) || path.equals("/")) {
            httpRequest.getRequestDispatcher("/static/index.html").forward(request, response);
        } else if (path.startsWith("/api/fizz-manager")) {


            path = path.substring("/api/fizz-manager".length());
            httpRequest.getRequestDispatcher(path).forward(request, response);
        } else if (path.startsWith("/fizz-manager")) {
            path = path.substring("/fizz-manager".length());
            httpRequest.getRequestDispatcher(path).forward(request, response);
        } else if (!path.startsWith("/static")) {
            path = String.format("%s%s", "/static", path);
            httpRequest.getRequestDispatcher(path).forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }
}
